﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace RFW.Silverlight.CurrentWeather
{
	public partial class MainPage : UserControl
	{
		private DispatcherTimer _timer = null;
		private RFW.Silverlight.Weather.CurrentConditions _weatherData = null;

		public MainPage()
		{
			InitializeComponent();
		}

		private void UserControl_Loaded(object sender, RoutedEventArgs e)
		{
			_timer = new DispatcherTimer();
			_timer.Interval = new TimeSpan(0, 0, 5);
			_timer.Tick += new EventHandler(timer_Tick);

			timer_Tick(this, EventArgs.Empty);
		}

		void timer_Tick(object sender, EventArgs e)
		{
			_timer.Stop();

			LoadData();
		}

		public Weather.CurrentConditions CurrentConditions
		{
			get { return _weatherData; }
		}

		private void LoadData()
		{
			if (_weatherData == null)
			{
				_weatherData = new Weather.PWS();
				_weatherData.DownloadComplete +=new EventHandler(_weatherData_DownloadComplete);
				_weatherData.DownloadFailed += new EventHandler(_weatherData_DownloadFailed);
			}

			_weatherData.Get();
		}

		void _weatherData_DownloadFailed(object sender, EventArgs e)
		{
			_timer.Start();
		}

		void _weatherData_DownloadComplete(object sender, EventArgs e)
		{
			wcWind.Direction = _weatherData.Wind.Direction;
			wcWind.Speed = _weatherData.Wind.Speed;

			ddTemp.Value = _weatherData.Temperature.F;
			ddHumidity.Value = _weatherData.Temperature.Humidity;
			ddPressure.Value = _weatherData.Pressure.IN;
			ddRainHour.Value = _weatherData.Rain.HourIN;
			ddRainToday.Value = _weatherData.Rain.TodayIN;

			_timer.Start();
		}
	}
}
